package com.regulareport.web.controller.report;

import com.regulareport.common.annotation.Log;
import com.regulareport.common.core.controller.BaseController;
import com.regulareport.common.core.domain.AjaxResult;
import com.regulareport.common.enums.BusinessType;
import com.regulareport.form.domain.rep.FillingEditRep;
import com.regulareport.form.domain.rep.ReportFillingQuery1Rep;
import com.regulareport.form.domain.req.BackReq;
import com.regulareport.form.domain.req.FillingEditReq;
import com.regulareport.form.domain.req.ReportFillingQueryReq;
import com.regulareport.form.service.impl.ReportFillingService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

@RestController
@RequestMapping("/report/filling")
@Api(tags = "报表填报")
public class ReportFillingController extends BaseController {
    private final ReportFillingService reportFillingService;
    private static final Logger logger = LoggerFactory.getLogger(ReportFillingController.class);
    public ReportFillingController(ReportFillingService reportFillingService) {
        this.reportFillingService = reportFillingService;
    }

    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:import')")
    @Log(title = "报表填报导入", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/import")
    public AjaxResult edit(MultipartFile file) {
        try {
            List<List<String>> lists = reportFillingService.importFile(file);
            StringBuilder err = getStringBuilder(lists);

            if (StringUtils.hasText(err.toString())) {
                return AjaxResult.error(err.toString());
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("报表填报导入", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    private StringBuilder getStringBuilder(List<List<String>> lists) {
        StringBuilder err = new StringBuilder();
        for (int i = 0; i < lists.size(); i++) {
            List<String> list = lists.get(i);
            for (int j = 0; j < list.size(); j++) {
                if (i != 0 && j == 1) {
                    err.append("/n");
                }
                if (j == list.size() -1) {
                    err.append(list.get(j));
                } else {
                    err.append(list.get(j)).append(",");
                }
            }
        }
        return err;
    }

    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:query')")
    @Log(title = "查询", businessType = BusinessType.QUERY)
    @PostMapping(value = "/query")
    public AjaxResult query(@RequestBody ReportFillingQueryReq req) {
        try {
            ReportFillingQuery1Rep reportFillingQueryRep = reportFillingService.query(req);
            return AjaxResult.success(reportFillingQueryRep);
        } catch (Exception e) {
            logger.error("查询", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:export')")
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @PostMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestBody ReportFillingQueryReq req) throws IOException {
        Path path;
        try {
            path = reportFillingService.export(req);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }
        if (path == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }
        // 1. 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(path.getFileName().toString(), "UTF-8"));

        // 2. 流式传输文件（适合大文件）
        try (InputStream in = Files.newInputStream(path.toFile().toPath());
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            logger.error("导出", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "文件下载失败: " + e.getMessage());
        }
    }


    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:bz')")
    @Log(title = "补零", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/bz")
    public AjaxResult bz( @RequestBody BackReq req) throws IOException {
        try {
            reportFillingService.bl(req);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("补零", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:back')")
    @Log(title = "补录", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/back")
    public AjaxResult back(@RequestPart("file") MultipartFile file, @RequestPart("req") BackReq req) throws IOException {
        try {
            reportFillingService.back(req, file);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("补录", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:backAll')")
    @Log(title = "批量补录", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/backAll")
    public AjaxResult backAll() {
        try {
            reportFillingService.backAll();
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("批量补录", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:bzAll')")
    @Log(title = "批量补零", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/bzAll")
    public AjaxResult blAll() {
        try {
            reportFillingService.blAll();
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("批量补零", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('report:filling:rollback')")
    @Log(title = "回退", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/rollback")
    public AjaxResult rollback(@RequestBody  BackReq req) {
        try {
            reportFillingService.rollback(req);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("回退", e);
            return AjaxResult.error(e.getMessage());
        }
    }

//    /**
//     * 导入总行表
//     */
//    @PreAuthorize("@ss.hasPermi('report:filling:excel')")
//    @Log(title = "测试excel", businessType = BusinessType.UPDATE)
//    @PostMapping(value = "/excel")
//    public AjaxResult excel(MultipartFile file) throws IOException {
//        try {
//            ExcelUtil1<ReportIndexAdditionalRecording> util = new ExcelUtil1<>(ReportIndexAdditionalRecording.class);
//            List<ReportIndexAdditionalRecording> recordings = util.importExcel(file.getInputStream());
//            reportFillingService.importRecordings(recordings);
////            reportFillingService.testExcel(f);
//            return AjaxResult.success();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error(e.getMessage());
//        }
//    }

//    /**
//     * 导入总行表
//     */
//    @PreAuthorize("@ss.hasPermi('report:filling:batchExport')")
//    @Log(title = "批量导出", businessType = BusinessType.EXPORT)
//    @PostMapping(value = "/batchExport")
//    public void batchExport(HttpServletResponse response, @RequestBody ReportFillingQueryBatchReq req) throws IOException {
//        Path path = null;
//        try {
//            path = reportFillingService.batchExport(req);
//        } catch (Exception e) {
//            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
//            return;
//        }
//        if (path == null) {
//            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
//            return;
//        }
//        // 1. 设置响应头
//        response.setContentType("application/octet-stream");
//        response.setHeader("Content-Disposition",
//                "attachment; filename=" + URLEncoder.encode(path.getFileName().toString(), "UTF-8"));
//
//        // 2. 流式传输文件（适合大文件）
//        try (InputStream in = new FileInputStream(path.toFile());
//             OutputStream out = response.getOutputStream()) {
//            byte[] buffer = new byte[1024];
//            int bytesRead;
//            while ((bytesRead = in.read(buffer)) != -1) {
//                out.write(buffer, 0, bytesRead);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
//                    "文件下载失败: " + e.getMessage());
//        }
//    }


    /**
     * 导入总行表
     */
    @PreAuthorize("@ss.hasPermi('report:filling:edit')")
    @Log(title = "编辑", businessType = BusinessType.QUERY)
    @PostMapping(value = "/edit")
    public AjaxResult edit(@RequestBody FillingEditReq req) {
        try {
            FillingEditRep fillingEditRep = reportFillingService.edit(req);
            return AjaxResult.success(fillingEditRep);
        } catch (Exception e) {
            logger.error("编辑", e);
            return AjaxResult.error(e.getMessage());
        }
    }



}
